package ace.tool.generate.code.impl.resolver.scheme.resolver;

import ace.cmp.util.CaseFormatUtils;
import ace.tool.generate.code.impl.resolver.scheme.model.dto.ClassFileInfo;
import java.util.HashMap;
import java.util.Map;
import lombok.Builder;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.WordUtils;
import org.apache.commons.text.StringSubstitutor;

/**
 * @author caspar
 * @date 2023/11/17 10:34
 */
@Builder
@RequiredArgsConstructor
public class ClassFileInfoResolver {

  /**
   * 源文件根目录
   */
  private final String sourceCodeRootDir;

  /**
   * 类名
   */
  private final String className;

  /**
   * 类名后缀
   */
  private final String classNameSuffix;

  /**
   * 类包相对路径前缀
   */
  private final String classPackagePrefix;

  /**
   * 类包根路径
   */
  private final String rootPackageFullName;

  public ClassFileInfo resolve() {
    String realClassName = this.getClassName();
    return ClassFileInfo.builder()
        .classFileFullName(this.getClassFileFullName())
        .classFullName(this.getClassFullName())
        .className(realClassName)
        .classPackageFullName(this.getClassPackageFullName())
        .classNameLowercaseDashName(this.getClassNameLowercaseDashName())
        .classNameFirstLowercase(this.getClassNameFirstLowercase(realClassName))
        .build();
  }

  private String getClassNameFirstLowercase(String realClassName) {
    return WordUtils.uncapitalize(realClassName);
  }

  public String getClassNameLowercaseDashName() {
    return CaseFormatUtils.convertUpperCamelToLowerUnderscore(className).replaceAll("_", "-");
  }

  public String getClassFileFullName() {
    Map<String, String> data = new HashMap<>();
    data.put("sourceCodeRootDir", this.sourceCodeRootDir);
    data.put("classFileFullName", this.getClassFullName().replace(".", "/"));
    return StringSubstitutor.replace("${sourceCodeRootDir}/${classFileFullName}.java", data);
  }

  public String getClassPackageFullName() {
    Map<String, String> data = new HashMap<>();
    data.put("rootPackageFullName", this.rootPackageFullName);
    data.put("classPackagePrefix", this.classPackagePrefix);
    return StringSubstitutor.replace("${rootPackageFullName}.${classPackagePrefix}", data);
  }

  public String getClassFullName() {
    Map<String, String> data = new HashMap<>();
    data.put("packageFullName", this.getClassPackageFullName());
    data.put("className", this.getClassName());
    return StringSubstitutor.replace("${packageFullName}.${className}", data);
  }

  public String getClassName() {
    Map<String, String> data = new HashMap<>();
    data.put("classNameSuffix", this.classNameSuffix);
    data.put("className", this.className);
    return StringSubstitutor.replace("${className}${classNameSuffix}", data);
  }
}
